{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#射击app"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "前面提到过，在这一章我们来做射击（shoot-em-up，简写shmup）app，一个快节奏的射击游戏，比魂斗罗简单许多。\n",
    "\n",
    "<!-- TEASER_END-->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![shmup](kbpic/9.1 shmup.png)\n",
    "\n",
    "做一个在屏幕上同时移动不同内容的游戏，需要大量的渲染来实现，在移动端（或多平台支持）也是如此。这一章我们就来做这些事情，上一章的知识和源代码已经带我们入了门。\n",
    "\n",
    "教学大纲如下：\n",
    "\n",
    "- 用Kivy的纹理图集（Texture atlases）完成本来需要用底层代码实现的纹理坐标值的设置工作\n",
    "- 继续用GLSL开发一个质点原型，然后用这个原型做不同的游戏角色\n",
    "- 实现二维射击游戏的——一个控件，鼠标和触摸屏，基本冲突发现子弹\n",
    "\n",
    "后面会涉及到大量细节，如果看不明白就运行一下文末的源代码。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##项目的限制\n",
    "\n",
    "我们做的app比较简单，功能有限，至少有以下限制：\n",
    "\n",
    "- 为了简化，忽略了奖惩机制，2048里面也是这样\n",
    "- 这个游戏只有一个敌人角色，简单模式\n",
    "- 许多优化被忽略了，可以少写一些代码\n",
    "\n",
    "如果感兴趣可以自己做。下面我们来看一下Kivy的纹理处理相关内容，后面会用到。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##纹理图集简介\n",
    "\n",
    "纹理图集（也叫sprite sheets）是一种应用开发中把图象组合成更大纹理的方法。与只是把一堆单个图象载入应用相比，这么做有些好处：\n",
    "\n",
    "- 应用打开更快，读一个大文件比读许多小文件要快。如果你有几百个这样的图片，用这种方法性能提升会很明显——网页上更是如此：图片太多会严重占用HTTP请求资源，在移动设备上这点更加明显\n",
    "- 一次性渲染也会很更快。用纹理映射可以只改变需要变化的纹理坐标，而不需要引起其他内容的变化\n",
    "- 当有一个大的模型时，像GLSL类的渲染，用纹理图集方法更适合。另外，纹理的坐标值更容易获取，也不需要二次绑定纹理\n",
    "\n",
    ">在HTML和CSS里面常用类似的方法，叫CSS图片合并（CSS sprites）。原理是一样的。网页app通常是获取网络资源，如果大量图片存在会占用HTTP请求数，用CSS图片合并可以很好的降低HTTP请求占用。\n",
    "\n",
    "这一章，我们要介绍以下内容：\n",
    "\n",
    "- 用Kivy的CLI工具创建纹理映射\n",
    "- 文件格式化和`.atlas`文件结构\n",
    "- Kivy应用纹理图集的用法\n",
    "\n",
    "如果你已经掌握了相关内容，可以直接跳到*GLSL使用纹理图集*一节。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###创建一个图集\n",
    "\n",
    "和网页开发不同，那里没有标准工具处理这个任务，Kivy框架用一个命令行工具处理图集映射。\n",
    "\n",
    "```bash\n",
    "python –m kivy.atlas <atlas_name> <texture_size> <images…>\n",
    "```\n",
    "\n",
    "在Mac系统上，把`python`替换成`kivy`，因为安装的时候`Kivy.app`会调用Python解释器。\n",
    "\n",
    "这样会创建至少两个文件，由所有的图像是否满足一个设定大小的纹理来决定。本章假设`texture_size`的值足够包含所有图像。\n",
    "\n",
    "所有输出文件都是`atlas_name`开头的参数：\n",
    "\n",
    "- 图集的索引称作`<atlas_name>.atlas`\n",
    "- 纹理有一个后缀`<atlas_name>-0.png`（这个文件总是存在的），`<atlas_name>-1.png`等等"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###图集结构"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`.atlas`是JSON格式的文件，用来描述纹理映射的位置。\n",
    "\n",
    "```json\n",
    "{\n",
    "    \"game-0.png\": {\n",
    "        \"player\": [2, 170, 78, 84],\n",
    "        \"bullet\": [82, 184, 24, 16]\n",
    "    }\n",
    "}\n",
    "```\n",
    "\n",
    "纹理的名称就是其源文件的文件名，没有后缀，`foo.png`就是`foo`。后面的数值对应的是`[x, y, width, height]`，所有值都是像素。\n",
    "\n",
    "组合纹理就是把一堆图片合并起来获得想要的内容，如下图所示。通常，为了利用空间会紧密排在一起。\n",
    "\n",
    ">创建图集的时候，Kivy谨慎会处理每个图集的边框，同时考虑图片可能因渲染后效果引起尺寸改变的情况。这就是为什么你需要为图片组合边距留出充分的像素。这样做效果并不可见，但是很有必要。\n",
    "\n",
    "![textureatlas](kbpic/9.2 textureatlas.png)\n",
    "\n",
    "在Kivy代码里面用图集的方法和`http`方式类似，`atlas://`后面跟图集的路径。如下所示：\n",
    "\n",
    "```yaml\n",
    "Image:\n",
    "    source: 'flags/Israel.png'\n",
    "```\n",
    "\n",
    "\n",
    "```yaml\n",
    "Image:\n",
    "    source: 'atlas://flags/Israel'\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###Kivy使用图集的简易方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要演示上面的方法，我们用前面用过的图标`icon_clock.png`和`icon_paint.png`来试试：\n",
    "\n",
    "![kivyatlas](kbpic/9.3 kivyatlas.png)\n",
    "\n",
    "要创建图集，我们用下面的命令：\n",
    "\n",
    "```bash\n",
    "kivy -m kivy.atlas icons 512 icon_clock.png icon_paint.png\n",
    "```\n",
    "\n",
    "如果不是Mac系统，用`python`命令。运行之后会出现如下提示：\n",
    "\n",
    "```\n",
    "[INFO] Kivy v1.9.1\n",
    "[INFO] [Atlas] create an 512x512 rgba image\n",
    "('Atlas created at', 'icons.atlas')\n",
    "1 image have been created\n",
    "```\n",
    "\n",
    "之后就会出现两个文件`icons.atlas`和`icons-0.png`。\n",
    "\n",
    ">现在可以删除源图片文件。不过最好还是保留，有可能后面更新图集的时候还会用到。\n",
    "\n",
    "图集准备好以后，我们来做一个简单的app。`basic.py`文件代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from kivy.app import App\n",
    "\n",
    "class BasicApp(App):\n",
    "    pass\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    BasicApp().run()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在`basic.kv`文件里面加载布局很简单：\n",
    "```yaml\n",
    "BoxLayout:\n",
    "    orientation: 'horizontal'\n",
    "    \n",
    "    Image:\n",
    "        source: 'atlas://icons/icon_clock'\n",
    "        \n",
    "    Image:\n",
    "        source: 'atlas://icons/icon_paint'\n",
    "```\n",
    "\n",
    "运行代码，效果如下图所示：\n",
    "\n",
    "![kivyatlaseasy](kbpic/9.4 kivyatlaseasy.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###在GLSL代码使用图集"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Kivy对图集的支持非常简单，但是GLSL应用里面没这么容易。好在`.atlas`是JSON格式，所以我们可以用Python的`json`模块来处理。然后，我们可以将像素坐标值转换成OpenGL的UV坐标值。\n",
    "\n",
    "由于我们知道每个纹理的绝对尺寸，我们可以计算出每个图片组合的顶点与中心的相对位置。这样就可以实现对图集按照其原始形式进行渲染，保持等比例变化。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####UV映射的数据结构"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "每个图集都有很多数据，为了方便管理数据，我们需要一个数据结构："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from collections import namedtuple\n",
    "\n",
    "UVMapping = namedtuple('UVMapping', 'u0 v0 u1 v1 su sv')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个数据类型和C语言的结构体类似，和下面的代码差不多："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class UVMapping:\n",
    "    def __init__(self, u0, v0, u1, v1, su, sv):\n",
    "        self.u0 = u0 # top left corner\n",
    "        self.v0 = v0 # ---\n",
    "        self.u1 = u1 # bottom right corner\n",
    "        self.v1 = v1 # ---\n",
    "        self.su = su # equals to 0.5 * width\n",
    "        self.sv = sv # equals to 0.5 * height"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，这些代码只是演示命名数组的原理，并不是完全相同。每个属性的定义如下：\n",
    "\n",
    "|属性|定义|\n",
    "|:-:|:-:|\n",
    "|`u0, v0`|图集左上角的UV坐标|\n",
    "|`u1, v1`|图集右下角的UV坐标|\n",
    "|`su`|图集宽度一半，在建立顶点数组的时候用|\n",
    "|`sv`|图集高度一半，在建立顶点数组的时候用|\n",
    "\n",
    "这样做让代码可读性更好，原来的`tup[3]`就可以用`tup.v1`表示。同时，`UVMapping`是元组类型，一种不可变的、内存结构合理的数据结构，可以通过索引连接所有属性。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####图集加载器"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，让我们写一个函数来描述图集加载的过程，包括处理JSON，确定坐标值等等。这个函数在程序的最后使用："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import json\n",
    "from kivy.core.image import Image\n",
    "\n",
    "def load_atlas(atlas_name):\n",
    "    with open(atlas_name, 'rb') as f:\n",
    "        atlas = json.loads(f.read().decode('utf-8'))\n",
    "        \n",
    "    tex_name, mapping = atlas.popitem()\n",
    "    tex = Image(tex_name).texture\n",
    "    tex_width, tex_height = tex.size\n",
    "    \n",
    "    uvmap = {}\n",
    "    for name, val in mapping.items():\n",
    "        x0, y0, w, h = val\n",
    "        x1, y1 = x0 + w, y0 + h\n",
    "        uvmap[name] = UVMapping(\n",
    "            x0 / tex_width, 1 - y1 / tex_height,\n",
    "            x1 / tex_width, 1 - y0 / tex_height,\n",
    "            0.5 * w, 0.5 * h)\n",
    "        \n",
    "    return tex, uvmap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">记住我们现在处理的是最简单的情况：一个图集由一个纹理构成。这也可能是最有效的配置方式，所以这个限制应该不会影响我们的代码，尤其是因为图集的生成完全在我们控制之下。\n",
    "\n",
    "因为坐标值是通过Kivy的坐标系统实现的，所有我们需要把纵坐标调整一下，用OpenGL的左上角为原点的坐标系统。否则，图集就会颠倒（不过，在我们的小游戏里面这不是什么大问题。这种bug可能要在代码里长期存在，虽然没被注意到，也没什么大碍）。\n",
    "\n",
    "`load_atlas('icons.atlas')`函数返回的是`icons-0.png`加载的纹理，和图集里每个纹理的UV描述，类似下面的结果：\n",
    "\n",
    "```bash\n",
    ">>> load_atlas('icons.atlas')\n",
    "\n",
    "(<Texture size=(512, 512)...>,\n",
    "{'icon_paint': UVMapping(u0=0.2578125, v0=0.00390625,\n",
    "                u1=0.5078125, v1=0.25390625,\n",
    "                su=64.0, sv=64.0),\n",
    "'icon_clock': UVMapping(...)})\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "有了这个数据格式，我们就可以从纹理中挑出每个合并图形然后渲染到屏幕上，下面就来实现。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####从图集中渲染合并图形"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "把上面的内容放到一起，我们用类似前面的GLSL纹理映射例子来实现一个新版本。\n",
    "\n",
    "这里的`tex_atlas.py`文件与上一章的内容类似。通过`load_atlas()`函数来生成订单数组："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from kivy.graphics import Mesh\n",
    "from kivy.graphics.instructions import RenderContext\n",
    "from kivy.uix.widget import Widget\n",
    "\n",
    "# ......\n",
    "class GlslDemo(Widget):\n",
    "    def __init__(self, **kwargs):\n",
    "        Widget.__init__(self, **kwargs)\n",
    "        self.canvas = RenderContext(use_parent_projection=True)\n",
    "        self.canvas.shader.source = 'tex_atlas.glsl'\n",
    "\n",
    "        fmt = (\n",
    "            (b'vCenter',     2, 'float'),\n",
    "            (b'vPosition',   2, 'float'),\n",
    "            (b'vTexCoords0', 2, 'float'),\n",
    "        )\n",
    "\n",
    "        texture, uvmap = load_atlas('icons.atlas')\n",
    "\n",
    "        a = uvmap['icon_clock']\n",
    "        vertices = (\n",
    "            128, 128, -a.su, -a.sv, a.u0, a.v1,\n",
    "            128, 128,  a.su, -a.sv, a.u1, a.v1,\n",
    "            128, 128,  a.su,  a.sv, a.u1, a.v0,\n",
    "            128, 128, -a.su,  a.sv, a.u0, a.v0,\n",
    "        )\n",
    "        indices = (0, 1, 2, 2, 3, 0)\n",
    "\n",
    "        b = uvmap['icon_paint']\n",
    "        vertices += (\n",
    "            256, 256, -b.su, -b.sv, b.u0, b.v1,\n",
    "            256, 256,  b.su, -b.sv, b.u1, b.v1,\n",
    "            256, 256,  b.su,  b.sv, b.u1, b.v0,\n",
    "            256, 256, -b.su,  b.sv, b.u0, b.v0,\n",
    "        )\n",
    "        indices += (4, 5, 6, 6, 7, 4)\n",
    "\n",
    "        with self.canvas:\n",
    "            Mesh(fmt=fmt, mode='triangles',\n",
    "                 vertices=vertices, indices=indices,\n",
    "                 texture=texture)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这点代码除了通常的GLSL初始化过程，就是把`load_atlas()`结果复制到`vertices`数组。我们选了两个不同的记录：`icon_clock`（用变量`a`表示）和`icon_paint`（用变量`b`表示），然后把它们放到顶点数组里。\n",
    "\n",
    "顶点数据格式包含以下内容：\n",
    "\n",
    "- **vCenter**：这是合并图片在屏幕上的位置，应该和指定合并图片的所有顶点有相同的值\n",
    "- **vPosition**：顶点与合并图片中心的相对位置，与`vCenter`无关\n",
    "- **vTexCoords0**：每个顶点的UV坐标值，决定纹理要渲染的部分\n",
    "\n",
    "只有合并图片的位置（数组的前两个数值）不能从UV映射关系中找到，其他数值都可以从`load_atlas()`获得。\n",
    "\n",
    "`tex_atlas.glsl`相关文件着色器代码如下：\n",
    "\n",
    "```C\n",
    "---vertex\n",
    "$HEADER$\n",
    "\n",
    "attribute vec2 vCenter;\n",
    "\n",
    "void main(void)\n",
    "{\n",
    "    tex_coord0 = vTexCoords0;\n",
    "    mat4 move_mat = mat4\n",
    "        (1.0, 0.0, 0.0, vCenter.x,\n",
    "         0.0, 1.0, 0.0, vCenter.y,\n",
    "         0.0, 0.0, 1.0, 0.0,\n",
    "         0.0, 0.0, 0.0, 1.0);\n",
    "    vec4 pos = vec4(vPosition.xy, 0.0, 1.0) * move_mat;\n",
    "    gl_Position = projection_mat * modelview_mat * pos;\n",
    "}\n",
    "\n",
    "---fragment\n",
    "$HEADER$\n",
    "\n",
    "void main(void)\n",
    "{\n",
    "    gl_FragColor = texture2D(texture0, tex_coord0);\n",
    "}\n",
    "```\n",
    "\n",
    "这里只有最简单的功能——定位和显示纹理。类似的着色器可以用在游戏最后，那时将增加一个控制相对大小的属性，`vScale`。\n",
    "\n",
    ">如果你不理解这段代码，请看看上一章的内容。\n",
    "\n",
    "最后运行程序的效果如下图所示：\n",
    "\n",
    "![atlasglsl](kbpic/9.5 atlasglsl.png)\n",
    "\n",
    "下面，我们来开发一个粒子系统作为整个游戏其他对象的基础。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "###设计重用粒子系统"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "当我们有很多类似的对象时，写一个具有简单功能的粒子系统是通用的做法。后面我们的飞船、子弹等等都用这个粒子系统来扩展。\n",
    "\n",
    "其实，上一章的屏保程序整个就是一个很好的粒子系统，不过还缺少一个配置能力，也不能轻易重用。因此，这里我们要改变这些GLSL代码。\n",
    "\n",
    ">值得一提的是，这里用的方法——每个粒子的四周用纹理渲染——并非底层渲染的最佳方案。但是，这么做非常直截了当，容易理解，而且与任何支持GLSL语言OpenGL的实现兼容。\n",
    "\n",
    ">如果你打算更系统的学习OpenGL，你可能会用把纹理的四周渲染改为点渲染，或者类似的概念，这已经超出的本书的范围。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "###类继续关系"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "粒子系统的API由两个类构成：`PSWidget`执行渲染，`Particle`类表示每个粒子。\n",
    "\n",
    "这两个类将与设计紧密耦合，在通常的OOP理论中这么做很有问题，但是可以改善我们app的性能：粒子可以直接连接渲染模块的顶点数组，来改变mesh网格——复制次数更少，考虑到需要同时处理很多粒子，这么做可以大大提升性能。\n",
    "\n",
    "粒子系统部件的实现和GLSL部件没什么不同，除了现在它是一个子类。`PSWidget`和`Particle`类都是抽象基类，也就是说，它们不能直接通过调用`PSWidget()`来实例化。\n",
    "\n",
    "增强这个现在有很多不同的方法。我们可以用Python标准模块`abc`来创建`true`抽象类（`abc`其实就是抽象类）。虽然这对Java程序员很有用，但是对Python程序员来说并不常用。\n",
    "\n",
    "为了简化，我们为所有需要改写的方法添加`NotImplementedError`异常处理。这使得基类没有元类和复杂的继承关系就不能使用，就像`abc`模块说明的那样。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "####PSWidget渲染类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "下面是`PSWidget`类代码："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class PSWidget(Widget):\n",
    "    indices = []\n",
    "    vertices = []\n",
    "    particles = []\n",
    "\n",
    "    def __init__(self, **kwargs):\n",
    "        Widget.__init__(self, **kwargs)\n",
    "        self.canvas = RenderContext(use_parent_projection=True)\n",
    "        self.canvas.shader.source = self.glsl\n",
    "\n",
    "        self.vfmt = (\n",
    "            (b'vCenter', 2, 'float'),\n",
    "            (b'vScale', 1, 'float'),\n",
    "            (b'vPosition', 2, 'float'),\n",
    "            (b'vTexCoords0', 2, 'float'),\n",
    "        )\n",
    "\n",
    "        self.vsize = sum(attr[1] for attr in self.vfmt)\n",
    "\n",
    "        self.texture, self.uvmap = load_atlas(self.atlas)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这和前面的GLSL初始化类似，有一些属性尚未定义。`self.glsl`属性将加载着色器的文件名，`self.atlas`是纹理映射的文件名，被当作是纹理为渲染实例提供的唯一来源。\n",
    "\n",
    "这么我们还没有生成顶点数组：这件事留给子类去做。但是，我们应该提供一个简单的方式为派生类处理内部数据结构。因此，`make_particles`方法可以容易的加入大量类似粒子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def make_particles(self, Cls, num):\n",
    "    count = len(self.particles)\n",
    "    uv = self.uvmap[Cls.tex_name]\n",
    "\n",
    "    for i in range(count, count + num):\n",
    "        j = 4 * i\n",
    "        self.indices.extend((\n",
    "            j, j + 1, j + 2, j + 2, j + 3, j))\n",
    "\n",
    "        self.vertices.extend((\n",
    "            0, 0, 1, -uv.su, -uv.sv, uv.u0, uv.v1,\n",
    "            0, 0, 1,  uv.su, -uv.sv, uv.u1, uv.v1,\n",
    "            0, 0, 1,  uv.su,  uv.sv, uv.u1, uv.v0,\n",
    "            0, 0, 1, -uv.su,  uv.sv, uv.u0, uv.v0,\n",
    "        ))\n",
    "\n",
    "        p = Cls(self, i)\n",
    "        self.particles.append(p)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这`Cls`类的质点数量（`num`），把它们增加到部件的`self.particles`列表，然后同时生成`self.vertices`。每个粒子类型应该显示一个`tex_name`属性，用来在UV映射中查找出正确的合并图片，这个数据结构由前面的图集（`PSWidget.uvmap`）派生出来。\n",
    "\n",
    "其实，这个辅助函数是可选的，但是很有用。部件的具体类的在渲染之前的初始化阶段调用这个函数。\n",
    "\n",
    "这个部件基类的最后部分就是渲染函数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def update_glsl(self, nap):\n",
    "    for p in self.particles:\n",
    "        p.advance(nap)\n",
    "        p.update()\n",
    "\n",
    "    self.canvas.clear()\n",
    "\n",
    "    with self.canvas:\n",
    "        Mesh(fmt=self.vfmt, mode='triangles',\n",
    "             indices=self.indices, vertices=self.vertices,\n",
    "             texture=self.texture)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "从`canvas.clear()`调用开始的代码和前面的GLSL例子类似。前面这段代码是在迭代所有粒子时调用两个方法：`advance()`方法计算粒子的新状态（由粒子决定），`update()`保持顶点数组中必要的数据的同步。\n",
    "\n",
    ">这里主要是为了代码的可读性，并没有过多考虑性能，如果需要优化性能，有如下建议：\n",
    "\n",
    "> - 循环部分可以并行处理\n",
    "> - 代码还可以完全用另一个线程，不用每一帧都升级（优化可能应用到粒子选择的类，比如，不影响主程序背景色的填充物）\n",
    "\n",
    "这个方法更多的实现细节会在后面介绍。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "####`Particle`类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "下面的代码就是Particle类，表示每个合并图片。源自满天星app的`Star`类，没有运动部分（后面的子类会实现）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Particle:\n",
    "    x = 0\n",
    "    y = 0\n",
    "    size = 1\n",
    "\n",
    "    def __init__(self, parent, i):\n",
    "        self.parent = parent\n",
    "        self.vsize = parent.vsize\n",
    "        self.base_i = 4 * i * self.vsize\n",
    "        self.reset(created=True)\n",
    "\n",
    "    def update(self):\n",
    "        for i in range(self.base_i,\n",
    "                       self.base_i + 4 * self.vsize,\n",
    "                       self.vsize):\n",
    "            self.parent.vertices[i:i + 3] = (\n",
    "                self.x, self.y, self.size)\n",
    "\n",
    "    def reset(self, created=False):\n",
    "        raise NotImplementedError()\n",
    "\n",
    "    def advance(self, nap):\n",
    "        raise NotImplementedError()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "`self.parent`保存一个引用到父类`PSWidget`中，方便后面的信息交互。前面也出现过的`update()`方法，让多边形四个顶点的变化与粒子位置和比例保持同步（`x`，`y`和`size`属性）。\n",
    "\n",
    "这里还有一个方法没有出现在`Star`里面，就是` advance()`，它应该被改写，因为没有为屏幕改变设置默认的动作，完全由粒子决定如何变化。后面你会看到，粒子系统可以用来创建不同的效果。\n",
    "\n",
    "`reset()`方法是在粒子的生命周期的最后重新初始化粒子（比如，已经离开屏幕或用完TTL的粒子）。虽然这里都是粒子系统，但是任何系统都会有一些要被恢复到原始状态的粒子。另外，这里也没有设置默认的行为让我们调用，所有这个函数什么也没有。\n",
    "\n",
    ">从一个虚拟方法触发`NotImplementedError`错误是提醒开发者，可以在派生类里定义该方法的内容。我们也可以忽略后面两个方法，但是这样做有可能引发`AttributeError`错误。保留方法的定义，即使没有实现，也是很好的做法，可以减少其他开发者的猜测（或者过段时间再看代码的时候，会感觉一头雾水，不知道自己怎么写的）。\n",
    "\n",
    "`reset()`方法里面的`created`参数。一些粒子系统在第一次生成的时候可能需要额外的（或不同的）初始化过程。前面也有过类似的情况，如满天星app里面，星星在屏幕的右手边生成。如果我们不考虑*已生成*状态，所有的星星都会出现的屏幕的最右侧，而且有同样的横坐标`x`，看起来就是一条直线。这样的结果肯定不是我们想要的，所以我们让通过将`created`变量设置成`True`使得星星的位置完全随机，这样就会看到漂亮的初始分布了。\n",
    "\n",
    "调用`reset()`方法意味着后面重生的粒子会比第一次生成的多很多，所以把`created`变量设置成`False`。\n",
    "\n",
    "现在基类的工作都完成了。后面你会看到，游戏的实现会变得很简单。下面我们就用粒子系统来创建游戏的角色。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "##制作游戏"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "我们的app将用前面做好的模块来构建：根部件是`PSWidget`的子类叫`Game`，所有的游戏角色都由粒子系统`Particle`类派生出来。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from kivy.base import EventLoop\n",
    "from kivy.clock import Clock\n",
    "\n",
    "class Game(PSWidget):\n",
    "    glsl = 'game.glsl'\n",
    "    atlas = 'game.atlas'\n",
    "\n",
    "    def initialize(self):\n",
    "        pass\n",
    "    \n",
    "class GameApp(App):\n",
    "    def build(self):\n",
    "        EventLoop.ensure_window()\n",
    "        return Game()\n",
    "\n",
    "    def on_start(self):\n",
    "        self.root.initialize()\n",
    "        Clock.schedule_interval(\n",
    "            self.root.update_glsl, 60 ** -1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "这里用的两个文件解释如下：\n",
    "\n",
    "- `game.glsl`着色器和`starfield.glsl`是一样的\n",
    "- `game.atlas`纹理映射包含下列纹理：\n",
    "    - `star`：和上一章的星星一样\n",
    "    - `player`：朝向右边的飞船\n",
    "    - `trail`：飞船发射的火球\n",
    "    - `bullet`：飞船发射的炮弹\n",
    "    - `ufo`：外星人朝向左边\n",
    "    \n",
    "上面的代码还没有在屏幕上显示出来，因为我们还没有生成顶点数组，下面我们来实现它们。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "###实现星星"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "现在我再建一个简单的星空。这次它从右向左运动，和前面的Kivy Bird游戏一样。\n",
    "\n",
    "要创建一个简单的平行视差效果，我们把星星分成三个平面，然后让它们有不同的速度。一个平面上的星星比较多也比较大，快速移动，另一个比较少慢速移动。一旦星星飞出屏幕就在左边的随机位置重生。\n",
    "\n",
    "下面我们来实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from random import randint, random\n",
    "\n",
    "class Star(Particle):\n",
    "    plane = 1\n",
    "    tex_name = 'star'\n",
    "\n",
    "    def reset(self, created=False):\n",
    "        self.plane = randint(1, 3)\n",
    "\n",
    "        if created:\n",
    "            self.x = random() * self.parent.width\n",
    "        else:\n",
    "            self.x = self.parent.width\n",
    "\n",
    "        self.y = random() * self.parent.height\n",
    "        self.size = 0.1 * self.plane\n",
    "\n",
    "    def advance(self, nap):\n",
    "        self.x -= 20 * self.plane * nap\n",
    "        if self.x < 0:\n",
    "            self.reset()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "`tex_name`是必须有的，引用`game.atlas`里面的纹理。\n",
    "\n",
    "随机生成一个星星的位置和所属的平面，无论初始化（`created=True`）是否被调用。\n",
    "\n",
    "`advance()`方法就是一旦星星飞出屏幕就重生。\n",
    "\n",
    "为了使用粒子系统，我们需要用`PSWidget`类的`make_particles()`方法来增加一些星星。在`Game.initialize()`里面："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def initialize(self):\n",
    "    self.make_particles(Star, 200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "下面就可以看到效果图：\n",
    "\n",
    "![starfield](kbpic/9.6 starfield.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "###实现宇宙飞船"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "我们只需要一个宇宙飞船（单人模式），用一个粒子就可以实现了。这么做是为了和后面的代码统一，这个对象的构建和其他对象没什么区别。\n",
    "\n",
    "飞船一直粘在鼠标位置，要实现这个效果，我们把鼠标的位置储存到`Game`属性里，用`player_x`和`player_y`来表示，然后把飞船图片加载到里面。代码如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from kivy.core.window import Window\n",
    "\n",
    "class Game(PSWidget):\n",
    "    def update_glsl(self, nap):\n",
    "        self.player_x, self.player_y = Window.mouse_pos\n",
    "        \n",
    "        PSWidget.update_glsl(self, nap)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "由于飞船实在用户的控制之下，没有其他逻辑要实现，只要把图片移动到鼠标位置就可以了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Player(Particle):\n",
    "    tex_name = 'player'\n",
    "    \n",
    "    def reset(self, created=False):\n",
    "        self.x = self.parent.player_x\n",
    "        self.y = self.parent.player_y\n",
    "        \n",
    "    advance = reset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你会发现`reset()`和`advance()`方法是一样的。还有飞船的初始化："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def initialize(self):\n",
    "    self.make_particles(Star, 200)\n",
    "    self.make_particles(Player, 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面就是效果图：\n",
    "\n",
    "![spaceship](kbpic/9.7 spaceship.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###实现飞船的尾巴或火焰"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "科幻小说里面的飞船都跟着一个尾巴。这个尾巴用下面的算法实现：\n",
    "\n",
    "1. 粒子在引擎附件生成，尺寸是随机的。粒子的尺寸也是它的存活时间（time to live，TTL）\n",
    "2. 它以一个恒定的速度飞离飞船，尺寸不断减小\n",
    "3. 最终粒子的尺寸会比原来小10%\n",
    "\n",
    "当有很多粒子来时，这个效果会很好看。不过截屏是看不出来了，你可以运行一下代码试试。代码如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Trail(Particle):\n",
    "    tex_name = 'trail'\n",
    "\n",
    "    def reset(self, created=False):\n",
    "        self.x = self.parent.player_x + randint(-30, -20)\n",
    "        self.y = self.parent.player_y + randint(-10, 10)\n",
    "\n",
    "        if created:\n",
    "            self.size = 0\n",
    "        else:\n",
    "            self.size = random() + 0.6\n",
    "\n",
    "    def advance(self, nap):\n",
    "        self.size -= nap\n",
    "        if self.size <= 0.1:\n",
    "            self.reset()\n",
    "        else:\n",
    "            self.x -= 120 * nap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "其实现方式很简单，用同样的`player_x`和`player_y`属性来决定飞船的位置。在初始化阶段，添加许多粒子来实现效果："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def initialize(self):\n",
    "    self.make_particles(Star, 200)\n",
    "    self.make_particles(Trail, 200)\n",
    "    self.make_particles(Player, 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "截图效果如下所示：\n",
    "\n",
    "![spaceshiptail](kbpic/9.8 spaceshiptail.png)\n",
    "\n",
    "还有敌人和子弹两个粒子系统没有实现。和前面看到的角色不同，它们都是在某个时间立刻出现，而敌人和子弹不是立刻出现的，两者都需要等一个特定的事件发生，然后逐渐增加数量，发射一颗子弹或者生成一个敌人。\n",
    "\n",
    "但是，之前我们需要分配固定数量的粒子，因为顶点数组的增减会让代码变得复杂，这不是我们想要的。\n",
    "\n",
    "方法是给粒子增加一个新的布尔变量属性，决定粒子是否属于激活状态，然后激活需要的粒子。这个方法后面会提到。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实现子弹"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们想让飞船的大炮在我们单击鼠标或触摸屏幕的时候能够发射子弹。用`firing`属性就可以实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Game(PSWidget):\n",
    "    firing = False\n",
    "    fire_delay = 0\n",
    "    \n",
    "    def on_touch_down(self, touch):\n",
    "        self.firing = True\n",
    "        self.fire_delay = 0\n",
    "        \n",
    "    def on_touch_up(self, touch):\n",
    "        self.firing = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "要在两次射击之间增加延迟，我们引入一个变量`fire_delay`。这个变量会按帧递减到0，然后一个新的子弹生成，`fire_delay`开始增大。在`firing`变量为`True`的时候循环："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def update_glsl(self, nap):\n",
    "    self.player_x, self.player_y = Window.mouse_pos\n",
    "    \n",
    "    if self.firing:\n",
    "        self.fire_delay -= nap\n",
    "        \n",
    "    PSWidget.update_glsl(self, nap)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，让我们看看这个粒子的状态。开始的时候，所有的子弹都没激活（` active=False`），移出屏幕（坐标值`x=-100, y=-100`设置子弹位置，可以在渲染的时候不让它们出现）。代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Bullet(Particle):\n",
    "    active = False\n",
    "    tex_name = 'bullet'\n",
    "    \n",
    "    def reset(self, created=False):\n",
    "        self.active = False\n",
    "        self.x = -100\n",
    "        self.y = -100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当遍历所有子弹之后，我们跳过那些没激活的子弹，保留`firing_delay`不是0的子弹。这时，我们激活一个子弹，然后把它放到玩家面前，启动`firing_delay`变量到倒计时。\n",
    "\n",
    "激活的子弹想星星一样移动，与星星方向相反。不像星星，子弹飞出屏幕后不会重生。它们回到不激活状态，从屏幕上消失。代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def advance(self, nap):\n",
    "    if self.active:\n",
    "        self.x += 250 * nap\n",
    "        if self.x > self.parent.width:\n",
    "            self.reset()\n",
    "    \n",
    "    elif (self.parent.firing and \n",
    "          self.parent.fire_delay <= 0):\n",
    "        self.active = True\n",
    "        self.x = self.parent.player_x + 40\n",
    "        self.y = self.parent.player_y\n",
    "        self.parent.fire_delay += 0.3333"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`fire_delay`属性设置为1/3秒，子弹发射的频率是每秒三发（3 rounds per second，RPS）。效果如下图所示：\n",
    "\n",
    "![spaceshipguns](kbpic/9.9 spaceshipguns.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###实现敌人"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "敌人的概念和子弹类似，但是它们是连续出现的，我们不需要`firing`这样的标记，用一个`spawn_delay`就够了。代码实现如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Game(PSWidget):\n",
    "    spawn_delay = 1\n",
    "    \n",
    "    def update_glsl(self, nap):\n",
    "        self.player_x, self.player_y = Window.mouse_pos\n",
    "        \n",
    "        if self.firing:\n",
    "            self.fire_delay -= nap\n",
    "            \n",
    "        self.spawn_delay -= nap\n",
    "        PSWidget.update_glsl(self, nap)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在初始化阶段，我们创建了一个预定义数量的敌人，开始不激活。为了实现后面对子弹的碰撞检测，我们需要存储一个子弹列表（`Game.particles`）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def initialize(self):\n",
    "    self.make_particles(Star, 200)\n",
    "    self.make_particles(Trail, 200)\n",
    "    self.make_particles(Player, 1)\n",
    "    self.make_particles(Enemy, 25)\n",
    "    self.make_particles(Bullet, 25)\n",
    "    self.bullets = self.particles[-25:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这些代码看着很复杂，因为这里涉及到很多不同的运动状态。为了固定`x`方向的速度，每个敌人还带一个随机垂直运动矢量`v`。当这样的粒子从屏幕边上的顶部到底部离开屏幕时，粒子的`v`属性不断改变，在屏幕上看到的是敌人又回到屏幕的效果。\n",
    "\n",
    "其他的规则与子弹类似：当敌人到达屏幕的底部，它重置然后消失再重生。代码如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "class Enemy(Particle):\n",
    "    active = False\n",
    "    tex_name = 'ufo'\n",
    "    v = 0\n",
    "\n",
    "    def reset(self, created=False):\n",
    "        self.active = False\n",
    "        self.x = -100\n",
    "        self.y = -100\n",
    "        self.v = 0\n",
    "\n",
    "    def advance(self, nap):\n",
    "        if self.active:\n",
    "            if self.check_hit():\n",
    "                snd_hit.play()\n",
    "\n",
    "                self.reset()\n",
    "                return\n",
    "\n",
    "            self.x -= 200 * nap\n",
    "            if self.x < -50:\n",
    "                self.reset()\n",
    "                return\n",
    "\n",
    "            self.y += self.v * nap\n",
    "            if self.y <= 0:\n",
    "                self.v = abs(self.v)\n",
    "            elif self.y >= self.parent.height:\n",
    "                self.v = -abs(self.v)\n",
    "\n",
    "        elif self.parent.spawn_delay <= 0:\n",
    "            self.active = True\n",
    "            self.x = self.parent.width + 50\n",
    "            self.y = self.parent.height * random()\n",
    "            self.v = randint(-100, 100)\n",
    "            self.parent.spawn_delay += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这段代码的设计思路很简单：\n",
    "\n",
    "1. 检查是否被一个子弹击中，或者要重置\n",
    "2. 水平移动，检查是否离开了屏幕，然后重置\n",
    "3. 垂直移动，检查是否离开了屏幕，改变速度矢量\n",
    "4. 如果`spawn_delay`已经到0，就重生一个敌人，然后启动`spawn_delay`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####碰撞检测"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们还没实现的`Enemy`类的另一个有趣功能是`check_hit()`方法。有两种情况敌人会撞到：飞船和子弹。为了简化，我们设定玩家是无敌的，敌人碰到任何物体都会被消灭："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def check_hit(self):\n",
    "    if math.hypot(self.parent.player_x - self.x,\n",
    "                  self.parent.player_y - self.y) < 60:\n",
    "        return True\n",
    "\n",
    "    for b in self.parent.bullets:\n",
    "        if not b.active:\n",
    "            continue\n",
    "\n",
    "        if math.hypot(b.x - self.x, b.y - self.y) < 30:\n",
    "            b.reset()\n",
    "            return True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`math.hypot()`是计算两物体中心距离，我们假设所有的物体都以这个方法监测。不能用没激活的子弹碰撞（`if not b.active`），因为没激活的子弹在屏幕上是看不到的。因此，它们不会在屏幕上撞击任何物体。\n",
    "\n",
    "这样游戏就完成了。\n",
    "\n",
    "![fullgame](kbpic/9.10 fullgame.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##改善功能"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "游戏有很多地方可以改进，尤其是游戏玩法上。当然这只是一个原型，不是商品，可以慢慢改进。\n",
    "\n",
    "如果你感兴趣，下面的建议留给你完成：\n",
    "\n",
    "- 游戏需要一个“Game Over”状态。胜利的状态不一定有，失败必须有，和上一章的类似\n",
    "- 增加角色，实现多种敌人，更多攻击的方式，也可以让敌人攻击飞船，增加关卡的难度，照着街机雷电游戏去做就行\n",
    "- 增加声音效果，可以仿照Kivy Bird那一章的内容。`MultiAudio`类也可以重用"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##总结"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这章的重点是用粒子系统来实现不同的游戏角色。这可能不是你了解的最好方法，但还是让我们把细节放下，来总结一下整本书的重点。\n",
    "\n",
    "一路走来，我们基本上学完了Python和Kivy游戏开发的过程，能胜任的领域很多：\n",
    "\n",
    "- 桌面和移动应用开发\n",
    "- 文字、图像、声音合成内容等应用的开发\n",
    "- 网络聊天应用的开发，以及社交网络，远程控制等程序\n",
    "- 视频游戏开发\n",
    "\n",
    "通过这本书，我们还为如何有效使用新技术提供了一些基本原则：\n",
    "\n",
    "- 把其他领域的经验迁移过来。Kivy虽然不一样，但并非完全不同，很多其他领域的方法都可以在这里重用\n",
    "- 努力探索实现的过程。理解框架工作的内部原理可以为调试提供极大帮助。\n",
    "- 如果文档缺失，请读源代码。毕竟，它是Python。\n",
    "- 遇到问题请用搜索引擎。你遇到的问题别人也遇到过。\n",
    "\n",
    "总之，我们衷心希望你能喜欢这次旅程。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[源代码](kbpic/src/9_ShootEmUp/)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
